﻿using System.Text;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyCompany.MyProject.Common.Helper;
using MyCompany.MyProject.IService;
using MyCompany.MyProject.Model;
using MyCompany.MyProject.Model.Models;
using MyCompany.MyProject.WebApi.ModelDto.DepartmentDto;
using Newtonsoft.Json;

namespace MyCompany.MyProject.WebApi.Controllers;

/// <summary>
/// 部门控制器
/// </summary>
public class DepartmentController : BasePermissionApiController
{
    private readonly IDepartmentService _departmentService;
    private readonly IMapper _mapper;
    private readonly IWebHostEnvironment env;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="departmentService"></param>
    /// <param name="mapper"></param>
    /// <param name="env"></param>
    public DepartmentController(IDepartmentService departmentService, IMapper mapper, IWebHostEnvironment env)
    {
        _departmentService = departmentService;
        _mapper = mapper;
        this.env = env;
    }

    /// <summary>
    /// 获取部门树
    /// </summary>
    /// <param name="pid"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<DepartmentTree>> GetDepartmentTree(long pid = 0)
    {
        var departments = await _departmentService.Query(d => d.IsDeleted == false);
        var departmentTree = (from child in departments
                              where child.IsDeleted == false
                              orderby child.Id
                              select new DepartmentTree
                              {
                                  value = child.Id,
                                  label = child.Name,
                                  Pid = child.Pid,
                                  order = child.OrderSort
                              }).ToList();
        DepartmentTree root = new DepartmentTree()
        {
            value = 0,
            Pid = 0,
            label = "根节点"
        };
        departmentTree = departmentTree.OrderBy(d => d.order).ToList();

        RecursionHelper.LoopToAppendChildren(departmentTree, root, pid);
        return Success(root, "获取成功");
    }

    /// <summary>
    /// 获取部门列表树
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<PageModel<DepartmentVo>>> Get(int pageIndex = 1, int pageSize = 10, string key = "")
    {
        var res = await _departmentService.QueryPage(i => i.IsDeleted == false, pageIndex, pageSize, key);

        return Success(res.ConvertTo<DepartmentVo>(_mapper), "获取成功");
        // return Success(_mapper.Map<PageModel<DepartmentVo>>(res), "获取成功");
    }

    /// <summary>
    /// 查询树形
    /// </summary>
    /// <param name="f"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public async Task<MessageModel<List<DepartmentVo>>> GetTreeTable(long f = 0, string key = "")
    {
        var departments = new List<DepartmentVo>();
        var departmentList = await _departmentService.Query(d => d.IsDeleted == false);
        if (key != "")
        {
            var res = departmentList.Where(a => a.Name.Contains(key)).OrderBy(a => a.OrderSort).ToList();
            departments = _mapper.Map<List<DepartmentVo>>(res);
        }
        else
        {
            var res = departmentList.Where(a => a.Pid == f).OrderBy(a => a.OrderSort).ToList();
            departments = _mapper.Map<List<DepartmentVo>>(res);
        }
        foreach (var item in departments)
        {
            List<long> pidArr = new() { };
            var parent = departmentList.FirstOrDefault(d => d.Id == item.Id);
            while (parent != null)
            {
                pidArr.Add(parent.Id);
                parent = departmentList.FirstOrDefault(d => d.Id == parent.Pid);
            }
            pidArr.Reverse();
            pidArr.Insert(0, 0);
            item.PidArr = pidArr;
            item.HasChildren = departmentList.Where(d => d.Pid == item.Id).Any();
        }
        return Success(departments);
    }

    /// <summary>
    /// 新增单位
    /// </summary>
    /// <param name="department"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<MessageModel<string>> Post(DepartmentVo department)
    {
        var data = new MessageModel<string>();
        var id = await _departmentService.Add(_mapper.Map<Department>(department));
        //var id = await _departmentService.Add(department);
        data.success = id > 0;
        if (data.success)
        {
            data.response = id.ToString();
            data.msg = "添加成功";
        }
        return data;
    }
    /// <summary>
    /// 更新单位
    /// </summary>
    /// <param name="department"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<MessageModel<string>> Update(DepartmentVo department)
    {
        var data = new MessageModel<string>();
        data.success = await _departmentService.Update(_mapper.Map<Department>(department));
        if (data.success)
        {
            data.response = department.Id.ToString();
            data.msg = "更新成功";
        }
        return data;
    }

    /// <summary>
    /// 删除单位
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<MessageModel<string>> Delete(long id)
    {
        var data = new MessageModel<string>();
        var oldModel = await _departmentService.QueryById(id);
        if (oldModel != null)
        {
            oldModel.IsDeleted = true;
            data.success = await _departmentService.Update(oldModel);
            if (data.success)
            {
                data.response = oldModel.Id.ToString();
                data.msg = "删除成功";
            }
            return data;
        }
        data.success = false;
        data.msg = "删除的数据不存在";
        return data;
    }

    /// <summary>
    /// 根据数据生成文件
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<MessageModel<string>> SaveDataToTsv()
    {
        var data = new MessageModel<string>();
        if (env.IsDevelopment())
        {
            JsonSerializerSettings jsonSerializer = new JsonSerializerSettings()
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };
            var deptDatas = await _departmentService.Query(i => i.IsDeleted == false);
            var json = JsonConvert.SerializeObject(deptDatas, jsonSerializer);
            FileHelper.WriteFile(Path.Combine(env.WebRootPath, "SeedData", "Department.tsv"), json, Encoding.UTF8);
            data.success = true;
            data.msg = "生成成功";
        }
        else
        {
            data.success = false;
            data.msg = "当前处于生产环境，生成代码不可用";
        }
        return data;
    }

}
